package controllers;

import helpers.DateHelper;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import search.OrderSearchData;
import models.OrderModel;
import models.UserModel;

@SuppressWarnings("serial")
public class OrderManageServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(OrderManageServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		try {
			response.setCharacterEncoding("UTF-8");
			HttpSession session = request.getSession();
			UserModel user = (UserModel) session.getAttribute("user_logged_in");
			if (user != null) {
				OrderSearchData orderSearchData = new OrderSearchData();
				orderSearchData.searchByUser(user.getUsername());
				List<OrderModel> list = orderSearchData.getListResult();
				if (list != null && list.size() > 0) {
					request.setAttribute("orders", list);
					request.getRequestDispatcher("/pages/order_manager.jsp")
							.forward(request, response);
				} else {
					request.getRequestDispatcher("/pages/order_manager.jsp")
							.forward(request, response);
				}
			} else {
				request.setAttribute("sms", "Trang này không tồn tại hoặc bạn cần đăng nhập để truy cập.");
				request.getRequestDispatcher("/pages/no_cart.jsp").forward(
						request, response);
			}
		} catch (Exception e) {
			System.out.println("Error when try to manage order ! ");
			log.warning("Error when try to manage order ! ");
			e.printStackTrace();
			request.getRequestDispatcher("/pages/error.jsp").forward(request,
					response);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setCharacterEncoding("UTF-8");
			HttpSession session = request.getSession();
			UserModel user = (UserModel) session.getAttribute("user_logged_in");
			if (user != null) {
				List<OrderModel> list = new ArrayList<OrderModel>();
				String strTotalFrom = request.getParameter("totalFrom");
				String strTotalTo = request.getParameter("totalTo");
				String strPeriod = request.getParameter("period");
				String strFromDate = request.getParameter("fromDate");
				String strToDate = request.getParameter("toDate");
				String strOrderId = request.getParameter("orderId");
				int totalFrom = 0;
				int totalTo = 0;
				Date fromDate = null;
				Date toDate = null;
				if (strOrderId != null && !strOrderId.isEmpty()) {
					OrderSearchData orderSearchData = new OrderSearchData();
					orderSearchData.searchById(strOrderId);
					list.add(orderSearchData.getCurrentItem());
					strTotalFrom = "";
					strTotalTo = "";
					strPeriod = "A";
					strFromDate = "";
					strToDate = "";
				} else {
					try {
						totalFrom = Integer.parseInt(strTotalFrom);
					} catch (Exception e) {
						totalFrom = 0;
					}
					try {
						totalTo = Integer.parseInt(strTotalTo);
					} catch (Exception e) {
						totalTo = 0;
					}
					if (strPeriod != null && !strPeriod.isEmpty()) {
						if (!strPeriod.equals("A")) {
							DateFormat formatter = new SimpleDateFormat(
									"dd/MM/yyyy");
							try {
								fromDate = formatter.parse(strFromDate);								
							} catch (Exception e) {
								fromDate = null;
							}
							try {
								toDate = formatter.parse(strToDate);
								Calendar cal = Calendar.getInstance();
								cal.setTime(toDate);
								cal.set(cal.get(Calendar.YEAR),
										cal.get(Calendar.MONTH),
										cal.get(Calendar.DATE), 00, 00, 00);
								toDate = cal.getTime();
								if (fromDate.compareTo(toDate) > 0) {
									Date tempDate;
									tempDate = toDate;
									toDate = fromDate;
									fromDate = tempDate;
								}
							} catch (Exception e) {
								toDate = null;
							}
						}
						if (totalFrom > totalTo) {
							int tmp;
							tmp = totalTo;
							totalTo = totalFrom;
							totalFrom = tmp;
						}
					}					
					OrderSearchData orderSearch = new OrderSearchData();
					orderSearch.search(user.getUsername(), fromDate, toDate,
							totalFrom, totalTo);
					list = orderSearch.getListResult();
				}
				if (list != null) {
					request.setAttribute("orders", list);
				}
				request.setAttribute("totalFrom", String.valueOf(totalFrom));
				request.setAttribute("totalTo", String.valueOf(totalTo));
				request.setAttribute("strPeriod", strPeriod);
				request.setAttribute("fromDate",
						DateHelper.dateToString(fromDate, "dd/MM/yyyy"));
				request.setAttribute("toDate",
						DateHelper.dateToString(toDate, "dd/MM/yyyy"));
				request.getRequestDispatcher("/pages/order_manager.jsp")
						.forward(request, response);
			} else {
				request.getRequestDispatcher("/pages/error.jsp").forward(
						request, response);
			}
		} catch (Exception e) {
			System.out.println("Error when try to manage order ! ");
			log.warning("Error when try to manage order ! ");
			e.printStackTrace();
			request.getRequestDispatcher("/pages/error.jsp").forward(request,
					response);
		}
	}
}
